package com.fc.persistence.core;

import java.util.ArrayList;
import java.util.List;

import com.fc.persistence.exception.IDBException;
import com.google.code.morphia.Datastore;
import com.google.code.morphia.Morphia;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.ServerAddress;


public class IMongoClientImpl {
	private static MongoClient mongo;
	private static Morphia morphia;
	private static Datastore ds;
	protected IMongoClientImpl() {
		try{
			mongo = new MongoClient(getAddressList(),getMongoClientOptions());
			morphia = new Morphia();
			ds = morphia.createDatastore(mongo, MongoConfig.getDbName());
		}catch(Exception e){
			throw new IDBException(e.getMessage(),e.getCause());
		}
	}
	
	private List<ServerAddress> getAddressList(){
		List<ServerAddress> result = null;
		String host = MongoConfig.getHost();
		if(host != null && !host.isEmpty()){
			result = new ArrayList<ServerAddress>();
			String[] hs = host.trim().split(",");
			for(String str:hs){
				String[] tmp = str.trim().split(":");
				ServerAddress address = new ServerAddress(tmp[0], Integer.parseInt(tmp[1]));
				result.add(address);
			}
		}
		return result;
	}
	
	private MongoClientOptions getMongoClientOptions(){
		MongoClientOptions options = MongoClientOptions.builder().minConnectionsPerHost(MongoConfig.getMinConnectionsPerHost())
				.connectionsPerHost(MongoConfig.getMaxConnectionsPerHost())
				.heartbeatConnectTimeout(MongoConfig.getHeartbeatConnectTimeout())
				.heartbeatSocketTimeout(MongoConfig.getHeartbeatSocketTimeout()).build();
		return options;
	}
	
	protected Datastore getDatastore(){
		return ds;
	}
	
	protected void close(){
		mongo.close();
	}
	
}
